package comframe.jdbc.sql.support;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

import comframe.jdbc.sql.datasource.Config;
import comframe.jdbc.sql.datasource.ConnFactory;
import comframe.jdbc.sql.datasource.RayDataSource;
import comframe.jdbc.sql.proxy.JdbcProxy;

public class ExFacotry {
  private Config config = null;
  
  private String dataType;
  
  private RayDataSource dataSource;
  private boolean IsSingleton;
  private IEx iEx = null;
  public ExFacotry(Config fig){
	  dataType =  fig.getDataType();
	  this.config = fig;
	  this.IsSingleton = false;
  }
  
  public ExFacotry(RayDataSource dataSource) {
	  dataType = dataSource.getDataType();
	this.dataSource = dataSource;
	this.config = dataSource.getConfig();
	this.IsSingleton = false;
}

  public ExFacotry(Config fig,boolean IsSingleton){
	  dataType =  fig.getDataType();
	  this.config = fig;
	  this.IsSingleton = IsSingleton;
  }
  
  public ExFacotry(RayDataSource dataSource,boolean IsSingleton) {
	  dataType = dataSource.getDataType();
	this.dataSource = dataSource;
	this.config = dataSource.getConfig();
	this.IsSingleton = IsSingleton;
}



public IEx getEx(){
	if(IsSingleton){
		if(iEx == null){
			if(dataSource!=null){
				iEx = (IEx)Proxy.newProxyInstance(IEx.class.getClassLoader(),new Class[]{ IEx.class}, new JdbcProxy(new JdbcEx(dataSource,IsSingleton)));
			   }else if(config!=null){
				   iEx = (IEx)Proxy.newProxyInstance(IEx.class.getClassLoader(),new Class[]{ IEx.class}, new JdbcProxy(new JdbcEx(config,IsSingleton)));
			  }else{
				  iEx = (IEx)Proxy.newProxyInstance(IEx.class.getClassLoader(),new Class[]{ IEx.class}, new JdbcProxy(new JdbcEx(IsSingleton)));
			  }
		}
		return iEx;
	}else{
		if(dataSource!=null){
			   return (IEx)Proxy.newProxyInstance(IEx.class.getClassLoader(),new Class[]{ IEx.class}, new JdbcProxy(new JdbcEx(dataSource,IsSingleton)));
		   }else if(config!=null){
			  return (IEx)Proxy.newProxyInstance(IEx.class.getClassLoader(),new Class[]{ IEx.class}, new JdbcProxy(new JdbcEx(config,IsSingleton)));
		  }else{
			  return (IEx)Proxy.newProxyInstance(IEx.class.getClassLoader(),new Class[]{ IEx.class}, new JdbcProxy(new JdbcEx(IsSingleton)));
		  }
	}
  }

public Connection getConn() throws SQLException, ClassNotFoundException{
	   if(dataSource!=null){
		 return dataSource.createDataSource().getConnection();
	   }else if(config!=null){
		 return ConnFactory.getFactory().getConn(config);
	  }else{
		return null;
	  }
}

public String getDataType() {
	return dataType;
}

public void setDataType(String dataType) {
	this.dataType = dataType;
}

}
